
package net.biaji.android.alephclient.views;

import java.util.ArrayList;
import java.util.Date;

import net.biaji.alephclient.Book;
import net.biaji.android.alephclient.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

public class BookAdapter extends BaseAdapter {
    /**
     * 搜索结果
     */
    public static final int ADAPTER_TYPE_SEARCHRESULT = 2;

    private Context context;

    private ArrayList<Book> bookList;

    public BookAdapter(Context context, ArrayList<Book> list) {
        this.context = context;
        this.bookList = list;
    }

    @Override
    public int getCount() {
        return bookList == null ? 0 : bookList.size();
    }

    @Override
    public Object getItem(int position) {
        return bookList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public void clear() {
        bookList.clear();
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.book_list_item, null);
        }
        TextView bookName = (TextView) convertView.findViewById(R.id.bookTitle);
        TextView author = (TextView) convertView.findViewById(R.id.authors);
        TextView pubDate = (TextView) convertView.findViewById(R.id.return_date_expected);
        Button btnExtend = (Button) convertView.findViewById(R.id.extend);
        Book result = (Book) getItem(position);
        bookName.setText(result.getName());
        StringBuilder authors = new StringBuilder();

        for (String tmpAu : result.getAuthor()) {
            authors.append(" ").append(tmpAu);
        }

        if (result.getAuthor().size() == 0) {
            author.setVisibility(View.GONE);
        } else {
            pubDate.setVisibility(View.VISIBLE);
            author.setText(authors);
        }

        Date returnDateExpected = result.getReturnDateExpected();
        if (returnDateExpected == null) {
            pubDate.setVisibility(View.GONE);
        } else {
            pubDate.setVisibility(View.VISIBLE);
            pubDate.setText(String.format(context.getString(R.string.return_date_expected),
                    DateFormat.format("yyyy-MM-dd", returnDateExpected)));
            // btnExtend.setVisibility(View.VISIBLE);
        }
        return convertView;
    }
}
